<?php
namespace AdminBundle\Repository;


class TaskQueueWaitingRepository extends BaseRepository
{
    public function pageQuery($_params, $page)
    {

        $sql = <<<EOF
select 
    id, name, note, creator, ip, ctime, uri, method, action, params, 
    device_id as deviceId, device_Name as deviceName, device_group_id as deviceGroupId, webchat_username as webchatUsername
from task_queue_waiting 
where 1=1 
EOF;
        $params = array();
        if (!empty($_params)) {
            if (isset($_params['starttime'])) {
                $sql .= ' and ctime > :starttime ';
                $params['starttime'] = $_params['starttime'];
            }
            if (isset($_params['endtime'])) {
                $sql .= ' and ctime < :endtime ';
                $params['endtime'] = $_params['endtime'];
            }
            if (isset($_params['keyword']) && !empty($_params['keyword'])) {
                $sql .= ' and name like :keyword ';
                $params['keyword'] = '%' . $_params['keyword'] . '%';
            }
        }
        $sql .= ' ORDER BY id DESC';

        return $this->pageWithRawSql($sql, $params, $page);
    }

    public function cachePublish($params = [])
    {
        $query = $this->createQueryBuilder('q')
            ->where("q.ctime > :ctime")
             ->setParameter('ctime', $params['ctime'])
            ->orderBy('q.id', 'ASC')
            ->getQuery();

        return $query->getResult();
    }

    /**
     * 删除已经执行并汇报过的数据
     * @param $ids
     * @return bool|int
     * @throws \Exception
     */
    public function deleteDelivery($ids)
    {
        if (!is_array($ids) || empty($ids)) {
            return 0;
        }
        $ids_string = implode(',', $ids);
        $sql = <<<EOF
insert into task_queue_log(id, name, note, creator, ip, ctime, template_id, uri, method, action, params, device_id, device_group_id, webchat_username, device_name)
select id, name, note, creator, ip, ctime, template_id, uri, method, action, params, device_id, device_group_id, webchat_username, device_name 
from task_queue_waiting 
where id in ({$ids_string})
EOF;
        $this->rawExecute($sql);

        $sql = "delete from task_queue_waiting where id in (" . $ids_string . ")";

        return $this->rawExecute($sql);
    }

    /**
     * 获取自己要执行的任务
     * @param $userName
     * @return bool
     * @throws \Exception
     */
    public function fetchTaskByUserName($userName)
    {
        $sql = <<<EOF
SELECT 
    id,
    name,
    uri,
    params
FROM
    task_queue_waiting
WHERE
    webchat_username = :user_name
EOF;
        $params = ['user_name' => $userName];

        return $this->rawQuery($sql, $params);
    }
}
